package top.kaoshanji.ch05;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Method;

/**
 * 代码清单 ch05-06：调用任意方法和构造器(5.7.7节)
 * author kaoshanji
 * ^_^
 * create time 2024/11/26 18:27
 */
public class MethodTableTest {

    private static final Logger logger = LogManager.getLogger(MethodTableTest.class);

    public static void main(String[] args) throws ReflectiveOperationException {
        logger.info("...代码清单 ch05-06：调用任意方法和构造器(5.7.7节)...");

        Method square = MethodTableTest.class.getMethod("square", double.class);
        Method sqrt = Math.class.getMethod("sqrt", double.class);

        // print tables of x- and y-values
        printTable(1, 10, 10, square);
        printTable(1, 10, 10, sqrt);

    }

    public static double square(double x) {
        return x * x;
    }

    public static void printTable(double from, double to, int n, Method f) throws ReflectiveOperationException {

        System.out.println(f);

        double dx = (to - from) / (n - 1);

        for (double x = from; x <= to; x += dx) {

            // 第一个参数是对象，如果是静态的，就使用null
            double y = (Double) f.invoke(null, x);

            System.out.printf("%10.4f | %10.4f%n", x, y);
        }

    }



}
